import React, { useEffect } from 'react';
import { Table, Button, Space, Tooltip } from 'antd';
import { QuestionCircleFilled } from '@ant-design/icons';
import { useDeviceListColumns, useDevicesByIds } from '../../hooks';

/**
 * 已选择的设备列表
 */
function SelectedList(props) {
    const { readOnly, modelId, dataSource, onDelete } = props;

    const deviceListColumns = useDeviceListColumns({ defaultParams: [modelId] });
    const devicesByIds = useDevicesByIds(modelId, dataSource);

    const getColumns = () => {
        const columns = deviceListColumns.data ?? [];

        if (!readOnly) {
            columns.push({
                title: (
                    <Space size={4}>
                        操作
                        <Tooltip
                            title="操作栏的“删除”只是取消设备与验收单的关联关系，变更了设备的验收状态。"
                            placement="right"
                        >
                            <QuestionCircleFilled style={{ color: '#7486D9', fontSize: 12 }} />
                        </Tooltip>
                    </Space>
                ),
                render(record) {
                    return (
                        <Button
                            style={{ padding: 0 }}
                            type="link"
                            onClick={() => {
                                onDelete(record);
                            }}
                        >
                            删除
                        </Button>
                    );
                },
            });
        }

        return columns;
    };

    useEffect(() => {
        const {
            tableProps: {
                pagination: { current, pageSize },
                onChange,
            },
        } = devicesByIds;

        const data = dataSource ?? [];
        const currentPageData = data.slice(pageSize * (current - 1), pageSize * current);
        const nextCurrent = currentPageData.length ? current : Math.max(1, Math.ceil(data.length / pageSize));

        onChange({ current: nextCurrent, pageSize });
    }, [dataSource]);

    return (
        <Table
            rowKey="cm_unid"
            scroll={{ x: 'max-content' }}
            locale={{ emptyText: readOnly ? undefined : '暂无数据，请添加验收设备' }}
            columns={getColumns()}
            {...devicesByIds.tableProps}
            loading={deviceListColumns.loading || devicesByIds.tableProps.loading}
            pagination={{
                showSizeChanger: true,
                showTotal: (total) => `共 ${total} 条`,
                ...devicesByIds.tableProps.pagination,
            }}
        />
    );
}

export default SelectedList;
